package DAO;

import bean.SubCategory;

import java.util.List;

public class SubCategoryDao extends BaseDao {
    public List<SubCategory> getAllSubCategories() {
        String sql = "SELECT id, name, category_id, description FROM sub_category";
        List<SubCategory> subCategories = queryForList(sql, SubCategory.class);
        for (SubCategory subCategory : subCategories) {
            if (subCategory.getCategoryId() == null) {
                System.out.println("Warning: Found SubCategory with null categoryId: " + subCategory.getId());
            }
        }
        return subCategories;
    }

    public List<SubCategory> getSubCategoriesByCategoryId(Integer categoryId) {
        String sql = "SELECT id, name, category_id, description FROM sub_category WHERE category_id = ?";
        return queryForList(sql, SubCategory.class, categoryId);
    }

    public SubCategory getSubCategoryById(int id) {
        String sql = "SELECT * FROM sub_category WHERE id = ?";
        return queryForOne(sql, SubCategory.class, id);
    }
    
    public int addSubCategory(SubCategory subCategory) {
        if (subCategory.getCategoryId() == null) {
            throw new IllegalArgumentException("CategoryId cannot be null");
        }
        System.out.println("Adding subcategory to database: " + subCategory);
        
        String sql = "INSERT INTO sub_category (name, category_id, description) VALUES (?, ?, ?)";
        try {
            return update(sql, 
                subCategory.getName(),
                subCategory.getCategoryId(),
                subCategory.getDescription()
            );
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
    
    public int deleteSubCategory(Integer id) {
        String sql = "DELETE FROM sub_category WHERE id = ?";
        return update(sql, id);
    }

    public int addSubCategoryTelevisionRelation(int subCategoryId, int televisionId) {
        String sql = "INSERT INTO subcategory_television (sub_category_id, television_id) VALUES (?, ?)";
        return update(sql, subCategoryId, televisionId);
    }

    public void addSubCategory(String name, int categoryId) {
        String sql = "INSERT INTO sub_category (name, category_id) VALUES (?, ?)";
        update(sql, name, categoryId);
    }

    public void updateSubCategory(int id, String newName) {
        String sql = "UPDATE sub_category SET name = ? WHERE id = ?";
        update(sql, newName, id);
    }

    public boolean updateSubCategory(SubCategory subCategory) {
        String sql = "UPDATE sub_category SET name = ?, description = ? WHERE id = ?";
        return update(sql, subCategory.getName(), subCategory.getDescription(), subCategory.getId()) > 0;
    }
} 